from PIL import Image


def resize_image(image_field, width=400):
    """
    更改用户上传图片大小

    image_field: 为ImageField对象
    width: 为图片宽度
    """

    try:
        img = Image.open(image_field)
    # 文件系统中图片删除后会报错
    except FileNotFoundError:
        pass
    else:
        (x, y) = img.size
        new_x = width
        # 等比例缩小
        new_y = int(new_x * (y / x))
        # 高分辨率缩小
        resized_image = img.resize((new_x, new_y), Image.ANTIALIAS)
        resized_image.save(image_field.path)
